package com.dragon.modules.yuegou.service.impl.company;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.media.workbook.validate.ValidateException;
import com.dragon.modules.media.workbook.validate.ValidateResult;
import com.dragon.modules.yuegou.entity.company.CompanyEntity;
import com.dragon.modules.yuegou.entity.company.EmployeesEntity;
import com.dragon.modules.yuegou.entity.member.MemberEntity;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.CompanyCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.enums.company.EmployeesStatus;
import com.dragon.modules.yuegou.excel.company.EmployeeWorkbook;
import com.dragon.modules.yuegou.mapper.company.EmployeesMapper;
import com.dragon.modules.yuegou.model.company.Employees;
import com.dragon.modules.yuegou.model.member.Member;
import com.dragon.modules.yuegou.model.system.Document;
import com.dragon.modules.yuegou.model.wallet.MemberWallet;
import com.dragon.modules.yuegou.query.company.CompanyQuery;
import com.dragon.modules.yuegou.query.company.EmployeeListQuery;
import com.dragon.modules.yuegou.query.company.EmployeesQuery;
import com.dragon.modules.yuegou.query.member.MemberQuery;
import com.dragon.modules.yuegou.service.company.CompanyService;
import com.dragon.modules.yuegou.service.company.EmployeesService;
import com.dragon.modules.yuegou.service.member.MemberService;
import com.dragon.modules.yuegou.service.system.DocumentService;
import com.dragon.modules.yuegou.service.wallet.MemberWalletService;
import com.dragon.modules.yuegou.utils.PrivateStringUtils;
import com.dragon.modules.yuegou.web.Check;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业员工表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:40
 * @version 2.0
 */
@Service("compEmployeesService")
public class EmployeesServiceImpl
		extends ServiceImpl<EmployeesMapper, EmployeesEntity>
		implements EmployeesService {

	@Autowired
	private MemberService memberService;
	
	@Autowired
	private EmployeesMapper employeesMapper;
	
	@Autowired
	private MemberWalletService memberWalletService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private DocumentService documentService;

	private static final String INPORT_MES = "导入企业员工信息";
	
	@Override
	public IPage<Employees> search(PageRequest page, EmployeeListQuery query) {
		IPage<Employees> iPage = new Page<>(page.getPage(),page.getSize(),page.getCount());
		return baseMapper.search(iPage,query);
	}

	@Override
	public void saveEmployee(String name,String moblie,String busdId,String companyId,String employeesId) {
		if (PrivateStringUtils.isNotMobileNO(moblie)) {
			throw new DragonException(BusinessCode.PHONE_WRONG_FORMAT);
		}

		EmployeesQuery employeesQuery = new EmployeesQuery();
		employeesQuery.setMoblie(moblie);
		employeesQuery.setStatus(EmployeesStatus.ENABLED);
		employeesQuery.setDel(false);
		
		Employees employees = new Employees();
		employees.setId(employeesId);
		employees.setName(name);
		employees.setMoblie(moblie);
		employees.setCompanyId(companyId);
		

		if (StringUtils.isEmpty(employeesId)) {
			//判断该企业下是否有这个手机号
			Long count = count(employeesQuery.toQueryWrapper());
			if (count>0) {
				throw new DragonException(BusinessCode.MOBLIE_NAME_EXISTS);
			}
			employees = getMemWalId(employees,busdId);
			//插入企业会员信息
			save(employees);
		}else {
			List<EmployeesEntity> list = list(employeesQuery.toQueryWrapper());
			if (list.size()>0 && !list.get(0).getId().equals(employees.getId())) {
				throw new DragonException(BusinessCode.MOBLIE_NAME_EXISTS);
			}
			baseMapper.updateById(employees);
		}
	}

	/**
	 * 获取会员和钱包信息
	 * */
	private Employees getMemWalId(Employees employees, String busdId){
		//根据手机号查询会员信息
		MemberQuery memberQuery = new MemberQuery();
		memberQuery.setMobile(employees.getMoblie());
		List<MemberEntity> memberList = memberService.list(memberQuery.toQueryWrapper());

		Member mem = new Member();
		mem.setBusdId(busdId);
		mem.setMobile(employees.getMoblie());
		mem.setNickName(employees.getName());
		if (CollectionUtils.isEmpty(memberList)) {
			mem = memberService.createMember(mem,null,null,null);
		}else {
			mem.setId(memberList.get(0).getId());
		}
		//根据会员Id查询钱包信息
		MemberWallet memberWallet = memberWalletService.loadByMember(mem.getId());

		//为实体类设置会员Id、会员钱包Id
		employees.setMemberId(mem.getId());
		employees.setWalletId(memberWallet.getId());
		return employees;
	}

	@Override
	public Employees getEmployee(String employeeId) {
		EmployeesEntity entity = getById(employeeId);
		//获得单位信息
		CompanyEntity company = companyService.getById(entity.getCompanyId());

		Employees employees = new Employees(entity);
		employees.setCompanyName(company.getName());
		return employees;
	}

	@Override
	public Employees getEmployeesByMobile(String mobile) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		return this.getEmployeesByMobile(mobile,null);
	}


	@Override
	public Employees getEmployeesByMobile(String mobile,String companyId) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		EmployeesQuery query = new EmployeesQuery();
		query.setDel(false);
		query.setMoblie(mobile);
		if (!StringUtils.isEmpty(companyId)){
			query.setCompanyId(companyId);
		}
		query.setStatus(EmployeesStatus.ENABLED);
		List<EmployeesEntity> employeesList = list(query.toQueryWrapper());
		if (CollectionUtils.isEmpty(employeesList)){
			return new Employees();
		}
		return new Employees(employeesList.get(0));
	}

	@Override
	@Transactional
	public void export(String fileId) {
		List<ValidateResult> errors = new ArrayList<>();
		EmployeeWorkbook employeeWorkbook = documentService.readExcel(fileId,EmployeeWorkbook.class);
		List<Employees> employeesList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(employeeWorkbook.getEmployees())) {
			//验证手机号是否重复
			long phoneCount = employeeWorkbook.getEmployees().stream().map(EmployeeWorkbook.EmployeeRow::getPhone).distinct().count();
			if (phoneCount < employeeWorkbook.getEmployees().size()){
				throw new DragonException(CompanyCode.DUPLICATE_MOBILE_NUMBER_ERROR);
			}
			for (int i = 0; i < employeeWorkbook.getEmployees().size(); i++) {
				EmployeeWorkbook.EmployeeRow employeeRow = employeeWorkbook.getEmployees().get(i);
				this.chenkEmployeeRow(employeeRow,employeesList,errors,i);
			}
		}else {
			throw new DragonException(CompanyCode.EXCEL_DATA_NULL);
		}
		if(!errors.isEmpty()){
			throw new ValidateException(employeeWorkbook, errors);
		}

		if (employeesList.size() > 0){
			employeesList.stream().forEach(this::save);
		}
		
	}

	private void chenkEmployeeRow(EmployeeWorkbook.EmployeeRow employeeRow,List<Employees> employeesList,List<ValidateResult> errors,int i){
		ValidateResult result = null;

		if (employeeRow.getName().length() > 10) {
			result = new ValidateResult(INPORT_MES, "员工姓名", i+1, employeeRow.getName(), "员工姓名长度不能超过10");
			errors.add(result);
			return;
		}
		CompanyQuery companyQuery = new CompanyQuery();
		companyQuery.setName(employeeRow.getCompanyName());
		List<CompanyEntity> list = companyService.list(companyQuery.toQueryWrapper());
		if (list.size() <= 0) {
			result = new ValidateResult(INPORT_MES, "单位名称", i+1, employeeRow.getCompanyName(), "单位名称不存在");
			errors.add(result);
			return;
		}
		if (PrivateStringUtils.isNotMobileNO(employeeRow.getPhone())) {
			result = new ValidateResult(INPORT_MES, "手机号", i+1, employeeRow.getPhone(), "手机号格式不正确");
			errors.add(result);
			return;
		}
		//判断单位下是否已经存在该员工
		EmployeesQuery employeesQuery = new EmployeesQuery();
		employeesQuery.setCompanyId(list.get(0).getId());
		employeesQuery.setMoblie(employeeRow.getPhone());
		List<EmployeesEntity> employeess = list(employeesQuery.toQueryWrapper());
		if (employeess.size() > 0) {
			result = new ValidateResult(INPORT_MES, "手机号", i+1, employeeRow.getPhone(), "单位内已存在手机号");
			errors.add(result);
			return;
		}

		Employees employees = new Employees();
		employees.setName(employeeRow.getName());
		employees.setMoblie(employeeRow.getPhone());
		employees.setCompanyId(list.get(0).getId());
		employees = getMemWalId(employees,list.get(0).getBusdId());
		employeesList.add(employees);
	}


	@Override
	public Document downloadTemplate() {
		EmployeeWorkbook employeeWorkbook = new EmployeeWorkbook();
		return documentService.generateExcel("批量导入企业员工模板", employeeWorkbook);
	}

	@Override
	public Document downloadEmployees(EmployeeListQuery query){
		List<Employees> list = employeesMapper.search(query);
		EmployeeWorkbook employeeWorkbook = new EmployeeWorkbook();
		List<EmployeeWorkbook.EmployeeRow> employeeRowList = new ArrayList<>();
		if(list != null && list.size() > 0) {
			for (Employees employees : list){
				EmployeeWorkbook.EmployeeRow employeeRow = new EmployeeWorkbook.EmployeeRow();
				employeeRow.setPhone(employees.getMoblie());
				employeeRow.setCompanyName(employees.getCompanyName());
				employeeRow.setName(employees.getName());
				employeeRowList.add(employeeRow);
			}
		}
		employeeWorkbook.setEmployees(employeeRowList);
		return documentService.generateExcel("企业员工表", employeeWorkbook);
	}
	
}